package com.example.coffeejava.Service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.coffeejava.Dto.Result;
import com.example.coffeejava.Entity.Admin;
import com.example.coffeejava.Entity.User;
import com.example.coffeejava.Entity.UserHolder;
import com.example.coffeejava.Mapper.AdminMapper;
import com.example.coffeejava.Mapper.UserMapper;
import com.example.coffeejava.Service.AdminService;
import com.example.coffeejava.Service.UserService;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.example.coffeejava.utils.Constants.USER_SIGN_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Result sign() {
        // 1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2.获取日期
        LocalDateTime now = LocalDateTime.now();
        //3.获取token
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //4.获取今天是本月的第几天
        int dayofMonth = now.getDayOfMonth();
        //5.写入redis
        stringRedisTemplate.opsForValue().setBit(key, dayofMonth - 1, true);
        return Result.ok("成功");

    }

    public Result signcount() {
        // 1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2.获取日期
        LocalDateTime now = LocalDateTime.now();
        //3.获取token
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //4.获取今天是本月的第几天
        int dayofMonth = now.getDayOfMonth();
        List<Long> result=stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayofMonth)).valueAt(0)
        );
        System.out.println(result+"result");
        if(result == null || result.isEmpty()){
            return Result.ok(0);
        }
        Long num=result.get(0);
        if(num == null || num == 0){
            return Result.ok(0);
        }

        int count=0;
        while (true){
            if((num&1) == 0){
                break;
            } else{
                count++;
            }
            num>>>=1;
        }
        return Result.ok(count);

    }

}
